﻿using Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MiniPc.API.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PcProject.Application.Service.Userss;
using PcProject.Domain.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using TodoApi.Jwt;

namespace MiniPc.API.Controllers
{
    /// <summary>
    /// 用户登录控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize] //授权过滤
    public class UsersController : ControllerBase
    {
        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        private IUserService _userService;
        private readonly ITokenHelper _tokenHelper;
        /// <summary>
        /// 函数依赖注入
        /// </summary>
        /// <param name="userService"></param>
        /// <param name="tokenHelper"></param>
        public UsersController(IUserService userService,ITokenHelper tokenHelper)
        {
            _userService = userService;
            _tokenHelper = tokenHelper;
        }


        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="LoginName"></param>
        /// <param name="LoginPwd"></param>
        /// <returns></returns>
        //[AllowAnonymous]//表示一个特性，该特性用于标记在授权期间要跳过 System.Web.Mvc.AuthorizeAttribute 的控制器和操作
        [HttpPost]
        public IActionResult Login([FromForm]string LoginName, [FromForm]string LoginPwd)
        {
            try
            {
                int n = _userService.Login(LoginName, LoginPwd);
                if (n > 0)
                {
                    Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
                    {
                        {"LoginName",LoginName }
                    };
                    var res = new ReposeModel();
                    //用帮助类来生成JWT字符串，JWT字符串返回给浏览器
                    res.TnToken = _tokenHelper.CreateToken(keyValuePairs);

                    var guid = Guid.NewGuid().ToString(); //全球唯一标识符

                    RedisHelper.Set(guid, keyValuePairs, DateTime.Now.AddMinutes(2));
                                    //键值
                    res.Guids = guid;

                    return Ok(new { data = res, code = 200 });

                }
                else
                {
                    return Ok(new { data = n, code = 0 });
                }

            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 刷新页面
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult NewGuid(string guid)
        {
            //从redis里取出用户的claim信息
            var claims = RedisHelper.Get<Dictionary<string, string>>(guid);
            if (claims == null)
            {
                return Ok(new { code = -1 });
            }
            //重新生成新的token 
            return Ok(_tokenHelper.CreateToken(claims));

        }

        /// <summary>
        /// 测试微信小程序接收code
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult VCode([FromForm] string code)
        {
            WeiXinLogin weixin = new WeiXinLogin();
            weixin.AppId = "wxae42300f02f7f7f0";    //固定值，请参照小程序参数说明
            weixin.AppSecret = "d3c77a90be00054dc984a459b56207b5"; //固定值，请参照小程序参数说明
            weixin.Code = code; //不固定  

            //微信的接口  
            var url = JsonConvert.DeserializeObject(HCHelper.GetApi("get", "https://api.weixin.qq.com/sns/jscode2session?appid=" + weixin.AppId +
                    "&secret=" + weixin.AppSecret + "&js_code=" + weixin.Code + "&grant_type=authorization_code"));

            //定义集合接收循环值
            List<string> lst = new List<string>();

            foreach (var item in url as JObject)
            {
                lst.Add(item.Value.ToString());
            }

            //从集合中取出session_key和openid
            string session_key = lst[0];
            string openid = lst[1];

            //定义证件单元
            Claim[] claims = new Claim[]
            {
                //new Claim("session_key",session_key),
                new Claim("openid",openid),
            };

            //帮助类生成token令牌
            string token = "Bearer " + _tokenHelper.CreateJwtToken(claims);

            return Ok(new { Authorization = token });

        }
    }
}
